/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sales.hanserver.action.hancadso.purchaserequest.insert;

import br.com.sales.hanserver.action.hancadso.purchaserequest.consts.HanCadSOServerConsts;
import static br.com.sales.hanserver.dao.Dao.closeConn;
import static br.com.sales.hanserver.dao.Dao.getConn;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author v
 */
public class InsertNewRequestQuery {

    public InsertNewRequestQuery() {
    }

    protected void insertRequest(Timestamp dt_solicitacao, Timestamp dt_registro, Long nr_seq_pf, List<Map> products) {
        Connection conn = getConn();
        try {

            PreparedStatement preparedStmt = conn.prepareStatement(HanCadSOServerConsts.INSERT_REQUEST);
            preparedStmt.setTimestamp(1, dt_solicitacao);
            preparedStmt.setObject(2, nr_seq_pf);
            preparedStmt.setTimestamp(3, dt_registro);

            preparedStmt.executeUpdate();

            Statement select = getConn().createStatement();

            ResultSet rs = select.executeQuery(HanCadSOServerConsts.GET_MAX_SEQUENCE);

            Long sequence;
            rs.next();
            sequence = rs.getLong("SEQUENCE");

            for (Map item : products) {
                PreparedStatement preparedItemStmt = conn.prepareStatement(HanCadSOServerConsts.INSERT_REQUEST_ITEM);
                preparedItemStmt.setString(1, (String) item.get("ID_PRODUCT"));
                preparedItemStmt.setLong(2, sequence);
                preparedItemStmt.setString(3, (String) item.get("COUNT"));

                preparedItemStmt.executeUpdate();
            }

        } catch (Exception e) {
            Logger.getLogger(InsertNewRequestQuery.class.getName()).log(Level.SEVERE, "Error insert Request", e);
        } finally {
            closeConn();
        }
    }
}
